import {SPLIT_BLANK, SPLIT_COMMA} from "@/api/enum";
import {exportBaseUrl, request} from "@/utils/request";

/* 一次性token */
function onceToken(data, callback) {
    return request({
        url: '/auth/export_once_token',
        method: 'get',
        data,
        isUser: true,
        isEmpty: true,
    }, callback)
}

// 获取资源token
function getUploadKey(data, callBack) {
    return request({
        url: '/resource/gen_upload_token',
        method: 'get',
        data,
        isYarn: true,
        isEmpty: true,
    }, callBack);
}

// 上传文件
/*export function uploadFile(that, type, files, originalName, callback) {
    if(files.length <= 0) {
        that.$toast.fail("没有待上传的文件")
        return;
    }
    that.$toast.loading({
        message: '上传中...',
        forbidClick: true,
        loadingType: 'spinner',
    });
    getUploadKey({
        type: type,
        num: files.length,
    }, tokenRes => {
        if(tokenRes.code || tokenRes.code == 0) {
            that.$toast.fail(tokenRes.msg);
            return;
        }

        let fileNames = tokenRes.fileName.split(SPLIT_COMMA);
        files = files.map((f, i) => {
            if(typeof f == "string") {
                f = dataURLtoFile(f, fileNames[i]);
            }
            return f;
        });

        let form = new FormData();
        files.forEach(file => {
            form.append("files", file);
        });
        form.append("type", type);
        form.append("originalName", originalName);
        let oReqCos = new XMLHttpRequest()
        oReqCos.open('POST', process.env.VUE_APP_UPLOAD_URL + '/file_upload/upload')
        oReqCos.setRequestHeader('x-yd-access-token', tokenRes.accessToken);
        oReqCos.onload = () => {
            if (oReqCos.status === 200) {
                that.fullscreenLoading = false;
                let res = JSON.parse(oReqCos.response)
                if (res.code === 2000) {
                    that.$toast.success({
                        message: "上传成功",
                        onClose: () => {
                            if(callback) {
                                callback(res.data);
                            }
                        }
                    })
                }
            } else {
                that.$toast.fail("上传失败");
            }
        }
        oReqCos.send(form);
    });
}*/


// 上传图片
export function uploadPic(that, type, files, callback) {
    if(files.length <= 0) {
        that.$toast.fail("没有待上传的文件")
        return;
    }
    getUploadKey({
        type: type,
        num: files.length,
    }, tokenRes => {
        if(tokenRes.code || tokenRes.code == 0) {
            that.$toast.fail(tokenRes.msg);
            return;
        }

        let fileNames = tokenRes.fileName.split(SPLIT_COMMA);
        files = files.map((f, i) => {
            if(f.content) {
                f = dataURLtoFile(f.content, fileNames[i] + ".jpeg");
            }
            return f;
        });

        that.$toast.loading({
            message: '上传中...',
            forbidClick: true,
            loadingType: 'spinner',
        });
        let form = new FormData();
        files.forEach(file => {
            form.append("files", file);
        });
        form.append("type", type);
        let oReqCos = new XMLHttpRequest();
        oReqCos.open('POST', process.env.VUE_APP_UPLOAD_URL + '/file_upload/upload_pic')
        oReqCos.setRequestHeader('x-yd-access-token', tokenRes.accessToken);
        oReqCos.onload = () => {
            if (oReqCos.status === 200) {
                let res = JSON.parse(oReqCos.response)
                if (res.code === 2000) {
                    that.$toast.success({
                        message: "上传成功",
                        onClose: () => {
                            if(callback) {
                                callback(res.data);
                            }
                        }
                    })
                } else {
                    that.$toast.fail(res.msg);
                }
            } else {
                that.$toast.fail("上传失败");
            }
        }
        oReqCos.send(form);
    });
}

/* 加载图片 */
export function loadPicThumb(that, fileName, callback) {
    onceToken({}, resData => {
        if(resData.code || resData.code == 0) {
            that.$toast.fail(resData.msg);
            return;
        }
        /*that.$toast.loading({
            message: '加载小图中...',
            forbidClick: true,
            loadingType: 'spinner',
        });*/
        let url = exportBaseUrl("res") + '/res_thumb/' + fileName + '?accessToken=' + resData;
        let xhr = new XMLHttpRequest(), blob;
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.addEventListener("load", function () {
            if (xhr.status === 200) {
                blob = xhr.response;
                callback(genImgUrl(blob));
            } else {
                that.$toast.fail("加载失败");
            }
        }, false);
        xhr.addEventListener("error", function () {
            console.log("xhr_error------------>");
            that.$toast.fail("加载异常");
        }, false);
        xhr.addEventListener("timeout", function () {
            console.log("xhr_timeout------------>");
            that.$toast.fail("加载超时");
        }, false);
        xhr.send();
    })
}

/* 加载图片 */
export function loadPic(that, fileName, callback) {
    onceToken({}, resData => {
        if(resData.code || resData.code == 0) {
            that.$toast.fail(resData.msg);
            return;
        }
        that.$toast.loading({
            message: '加载大图中...',
            forbidClick: true,
            loadingType: 'spinner',
        });
        let url = exportBaseUrl("res") + '/res/' + fileName + '?accessToken=' + resData;
        let xhr = new XMLHttpRequest(), blob;
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.addEventListener("load", function () {
            if (xhr.status === 200) {
                blob = xhr.response;
                callback(genImgUrl(blob));
            } else {
                that.$toast.fail("加载失败");
            }
        }, false);
        xhr.addEventListener("error", function () {
            console.log("xhr_error------------>");
            that.$toast.fail("加载异常");
        }, false);
        xhr.addEventListener("timeout", function () {
            console.log("xhr_timeout------------>");
            that.$toast.fail("加载超时");
        }, false);
        xhr.send();
    })
}

function dataURLtoFile(dataUrl, filename) {
    let arr = dataUrl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
}

export function genImgUrl(data) {
    if(null == data || undefined == data) {
        return "";
    }
    let URL = window.URL || window.webkitURL;
    let imgURL = URL.createObjectURL(data);
    return imgURL;
}

// 本地图片
export function loadLocalPicFn(that, blob, callback) {
    // 创建一个新的 FileReader 对象
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => {
        // 将读取的数据转换为 base64 编码的字符串
        callback(reader.result);
        /*that.img.data.push({
            src: base64String,
            preSrc: [base64String],
        });*/
    };
    // 加载失败时
    reader.onerror = function () {
        that.$toast.fail("选择失败,请重试")
    };
}

/*
export function loadLocal4DataUrlFn(blobUrl) {
    return new Promise((resolve, reject) => {
        // 使用 fetch 获取 Blob 对象
        fetch(blobUrl)
            .then(response => response.blob())
            .then(blob => {
                // 使用 FileReader 将 Blob 转换为 Base64
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            })
            .catch(reject);
    });
}*/
